package com.ruoyi.member.service.impl;


import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.im.entity.IMGroup;
import com.ruoyi.im.entity.IMGroupMember;
import com.ruoyi.im.entity.IMUserArea;
import com.ruoyi.im.service.IMGroupMemberService;
import com.ruoyi.im.service.IMGroupService;
import com.ruoyi.integral.domain.CustomerPoint;
import com.ruoyi.integral.service.CustomerPointService;
import com.ruoyi.marketing.domain.RegisterMarketing;
import com.ruoyi.marketing.service.CouponService;
import com.ruoyi.marketing.service.RegisterMarketingService;
import com.ruoyi.member.dao.RegisterData;
import com.ruoyi.member.domain.UmsMember;
import com.ruoyi.member.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * 注册服务聚合接口实现
 */
@Service
public class RegisterServiceApiImpl implements RegisterServiceApi {

    /**
     * 日志
     */
    private Logger logger = LoggerFactory.getLogger(RegisterServiceApiImpl.class);

    /**
     * 注入注册服务
     */
    @Autowired
    private RegisterService registerService;

    /**
     * 注入注册营销服务
     */
    @Autowired
    private RegisterMarketingService registerMarketingService;

    /**
     * 注入会员积分服务
     */
    @Autowired
    private CustomerPointService customerPointService;

    /**
     * 注入优惠券服务
     */
    @Autowired
    private CouponService couponService;

    /**
     * 注入会员服务
     */
    @Autowired
    private IUmsMemberService customerService;

    @Autowired
    private com.ruoyi.im.service.IMUserAreaService IMUserAreaService;
    @Autowired
    private IMGroupService groupService;
    @Autowired
    private IMGroupMemberService groupMemberService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int registerCustomer(RegisterData registerData, String originCode) {
        String mobile =registerData.getMobile();
        logger.debug("registerCustomer and mobile :{} \r\n originCode{}", mobile,  originCode);

        //注册用户
        int res = registerService.registerCustomer(mobile, originCode, registerData);
        //注册成功后执行注册营销
        if (res > 0) {

            //根据手机号查找用户
            UmsMember customer = customerService.queryCustomerByNameInWriteDataSource(mobile);

            IMUserArea userArea = BeanUtils.beanCopy(registerData, IMUserArea.class);
            userArea.setUserId(customer.getId());
            IMUserAreaService.addUserArea(userArea);

            saveGroupMember(customer,userArea);
            //查找注册营销
            RegisterMarketing registerMarketing = registerMarketingService.queryRegisterMarketing();
            if (!ObjectUtils.isEmpty(registerMarketing)) {
                if (registerMarketing.isEffective()) {
                    //赠送积分
                    logger.info("registerCustomer success : present point");
                    customerPointService.addCustomerPoint(CustomerPoint.buildForRegister(customer.getId(), registerMarketing.getPointNum()));
                }
                if (registerMarketing.isCanReceiveCoupon()) {
                    //赠送优惠券
                    logger.info("registerCustomer success : present coupon");
                    couponService.receiveCoupon(customer.getId(), registerMarketing.getCouponId(), 2);
                }
            }
        }
        if (res == -3) {
            UmsMember customer = customerService.queryCustomerByNameInWriteDataSource(mobile);
            if(customer.getRecommended() != -1) {
                res = customerService.updatePasswordByMobile(mobile, String.format("%s%s", registerData.getPassword(), customer.getSalt()));
            }
        }
        return res;
    }


    private void saveGroupMember(UmsMember user, IMUserArea uarea){
        IMGroup cityGroup =this.groupService.getAreaGroup(uarea.getCity());
        IMGroup countyGroup =this.groupService.getAreaGroup(uarea.getCounty());
        IMGroup townGroup =this.groupService.getAreaGroup(uarea.getTown());
        IMGroup villageGroup =this.groupService.getAreaGroup(uarea.getVillage());
        //long idGroupMax = 0,idMemberMax = 0;
        long timeNow = System.currentTimeMillis()/1000;
        IMGroup imGroup = new IMGroup();
        imGroup.setType((byte)1);
        imGroup.setStatus((byte)0);

        IMGroupMember groupMember = new IMGroupMember();
        groupMember.setUserId(user.getId());
        groupMember.setStatus(0);

        if(cityGroup == null) {
            imGroup.setName(uarea.getCity());
            imGroup.setCreator(user.getId());
            imGroup.setParentCode(uarea.getProvinceCode());
            imGroup.setAreaCode(uarea.getCityCode());
            imGroup.setLevelCode((byte)1);
            imGroup.setUsercnt(1);
            imGroup.setVersion(1);
            imGroup.setCreated(timeNow);
            //idGroupMax = groupService.addGroup(imGroup);
            groupService.addGroup(imGroup);
            groupMember.setGroupId(imGroup.getId());
        } else {
            imGroup.setId(cityGroup.getId());
            imGroup.setUsercnt(cityGroup.getUsercnt()+1);
            imGroup.setUpdated(timeNow);
            imGroup.setVersion(cityGroup.getVersion()+1);
            groupService.updateGroup(imGroup);
            groupMember.setGroupId(cityGroup.getId());
        }
        List<IMGroupMember> cityGroupMemberList =groupMemberService.findGroupMember(groupMember);
        if(cityGroupMemberList.size() == 0) {
            //idMemberMax = groupMemberService.addGroupMember(groupMember);
            groupMember.setCreated(timeNow);
            groupMemberService.addGroupMember(groupMember);
        }

        IMGroup imGroup1 = new IMGroup();
        imGroup1.setType((byte)1);
        imGroup1.setStatus((byte)0);

        IMGroupMember groupMember1 = new IMGroupMember();
        groupMember1.setUserId(user.getId());
        groupMember1.setStatus(0);
        if(countyGroup == null) {
            //if (idGroupMax > 0) { idGroupMax = idGroupMax+1; imGroup1.setId(idGroupMax);}
            imGroup1.setName(uarea.getCounty());
            imGroup1.setCreator(user.getId());
            imGroup1.setParentCode(uarea.getCityCode());
            imGroup1.setAreaCode(uarea.getCountyCode());
            imGroup1.setLevelCode((byte)2);
            imGroup1.setUsercnt(1);
            imGroup1.setVersion(1);
            imGroup1.setCreated(timeNow);
            /*if (idGroupMax == 0) {
                idGroupMax = groupService.addGroup(imGroup1);
            } else {
                groupService.addGroup(imGroup1);
            }*/
            groupService.addGroup(imGroup1);
            groupMember1.setGroupId(imGroup1.getId());
        } else {
            imGroup1.setId(countyGroup.getId());
            imGroup1.setUsercnt(countyGroup.getUsercnt()+1);
            imGroup1.setUpdated(timeNow);
            imGroup1.setVersion(countyGroup.getVersion()+1);
            groupService.updateGroup(imGroup1);
            groupMember1.setGroupId(countyGroup.getId());
        }
        List<IMGroupMember> cGroupMemberList =groupMemberService.findGroupMember(groupMember1);
        if(cGroupMemberList.size() == 0) {
            /*if (idMemberMax > 0) {
                idMemberMax = idMemberMax+1;
                groupMember1.setId(idMemberMax);
                groupMemberService.addGroupMember(groupMember1);
            } else {
                idMemberMax = groupMemberService.addGroupMember(groupMember1);
            }*/
            groupMember1.setCreated(timeNow);
            groupMemberService.addGroupMember(groupMember1);
        }

        IMGroup imGroup2 = new IMGroup();
        imGroup2.setType((byte)1);
        imGroup2.setStatus((byte)0);

        IMGroupMember groupMember2 = new IMGroupMember();
        groupMember2.setUserId(user.getId());
        groupMember2.setStatus(0);

        if(townGroup == null) {
            //if (idGroupMax > 0) { idGroupMax = idGroupMax+1; imGroup2.setId(idGroupMax);}
            imGroup2.setName(uarea.getTown());
            imGroup2.setCreator(user.getId());
            imGroup2.setParentCode(uarea.getCountyCode());
            imGroup2.setAreaCode(uarea.getTownCode());
            imGroup2.setLevelCode((byte)3);
            imGroup2.setUsercnt(1);
            imGroup2.setVersion(1);
            imGroup2.setCreated(timeNow);
            /*if(idGroupMax == 0) {
                idGroupMax = groupService.addGroup(imGroup2);
            } else {
                groupService.addGroup(imGroup2);
            }*/
            groupService.addGroup(imGroup2);
            groupMember2.setGroupId(imGroup2.getId());
        } else {
            imGroup2.setId(townGroup.getId());
            imGroup2.setUsercnt(townGroup.getUsercnt()+1);
            imGroup2.setUpdated(timeNow);
            imGroup2.setVersion(townGroup.getVersion()+1);
            groupService.updateGroup(imGroup2);
            groupMember2.setGroupId(townGroup.getId());
        }
        List<IMGroupMember> tGroupMemberList =groupMemberService.findGroupMember(groupMember2);
        if(tGroupMemberList.size() == 0) {
            /*if (idMemberMax > 0) {
                idMemberMax = idMemberMax+1;
                groupMember2.setId(idMemberMax);
                groupMemberService.addGroupMember(groupMember2);
            } else {
                idMemberMax = groupMemberService.addGroupMember(groupMember2);
            }*/
            groupMember2.setCreated(timeNow);
            groupMemberService.addGroupMember(groupMember2);
        }

        IMGroup imGroup3 = new IMGroup();
        imGroup3.setType((byte)1);
        imGroup3.setStatus((byte)0);

        IMGroupMember groupMember3 = new IMGroupMember();
        groupMember3.setUserId(user.getId());
        groupMember3.setStatus(0);

        if(villageGroup == null) {
            //if (idGroupMax > 0) { idGroupMax = idGroupMax+1; imGroup3.setId(idGroupMax);}
            imGroup3.setName(uarea.getVillage());
            imGroup3.setCreator(user.getId());
            imGroup3.setParentCode(uarea.getTownCode());
            imGroup3.setAreaCode(uarea.getVillageCode());
            imGroup3.setLevelCode((byte)4);
            imGroup3.setUsercnt(1);
            imGroup3.setVersion(1);
            imGroup3.setCreated(timeNow);
            groupService.addGroup(imGroup3);
            groupMember3.setGroupId(imGroup3.getId());
        } else {
            imGroup3.setId(villageGroup.getId());
            imGroup3.setUsercnt(villageGroup.getUsercnt()+1);
            imGroup3.setUpdated(timeNow);
            imGroup3.setVersion(villageGroup.getVersion()+1);
            groupService.updateGroup(imGroup3);
            groupMember3.setGroupId(villageGroup.getId());
        }
        List<IMGroupMember> vGroupMemberList =groupMemberService.findGroupMember(groupMember3);
        if(vGroupMemberList.size() == 0) {
            groupMember3.setCreated(timeNow);
            //if (idMemberMax > 0) { idMemberMax = idMemberMax+1; groupMember3.setId(idMemberMax);}
            groupMemberService.addGroupMember(groupMember3);
        }
    }
}



